import os
import uuid
from json import loads

from sanic import Blueprint, Request, json

from idcard_ocr.utils import ocr, oss

bp = Blueprint("api", url_prefix="/api")


@bp.post("/upload")
async def upload(request: Request):
    """上传文件"""
    filename, ext = os.path.splitext(request.json["filename"])
    filename = str(uuid.uuid4()) + ext
    content_type = request.json.get("content_type")
    url = await oss.make_upload_link(filename, content_type)
    return json(
        {
            "code": 0,
            "data": {
                "url": url,
                "key": filename,
            },
        }
    )


@bp.post("/ocr")
async def ocr_id_card(request: Request):
    """身份证识别"""
    key = request.json["key"]
    try:
        url = await oss.get_download_link(key)
        res = await ocr.id_card_ocr(url)
        res_dict = res.body.to_map()
        data = loads(res_dict["Data"])
    except Exception:
        data = {
            "code": -1,
            "msg": "身份证识别失败",
        }
    return json(
        {
            "code": 0,
            "data": data,
        },
    )
